//
//  RouteViewController.m
//  SXH
//
//  Created by 房 国生 on 15/7/23.
//  Copyright (c) 2015年 lyss. All rights reserved.
//

#import "RouteViewController.h"
#import "RouteTableViewCell.h"
#import "CommonService.h"
#import "UIImageView+WebCache.h"
#import "UIImageView+LK.h"
#import "RouteDetailViewController.h"


#import "RouteEntity.h"
#import "AppDelegate.h"
#import "ScanBarCodeViewController.h"
@interface RouteViewController ()<ScanBarCodeDelegate>
{
    MJRefreshHeaderView *_header;
    MJRefreshFooterView *_footer;
    int page;
}
@property (nonatomic, strong) IBOutlet UITableView *tableViewRouteProduce;

@property (nonatomic, strong) IBOutlet UILabel *labelTitle;
@end

#define K_cellIdentifier   @"RouteTableViewCell"

@implementation RouteViewController
@synthesize tableViewRouteProduce, mutableArrayRouteProduce;
@synthesize travelAgeEntity;

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.view.backgroundColor = LIGHTGARY;
    mutableArrayRouteProduce = [[NSMutableArray alloc] init];
    _labelTitle.text = travelAgeEntity.a_name;
    if (_labelTitle.text.length <=0) {
        _labelTitle.text = @"旅游路线";
    }
    page = 1;
    [self addHeader];
    [self addFooter];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

#pragma mark -
#pragma mark Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    // Return the number of sections.
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    // Return the number of rows in the section.
    return [mutableArrayRouteProduce count];
}

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    static NSString *couponTableViewCellIdentifier=K_cellIdentifier;
    RouteTableViewCell *cell = (RouteTableViewCell *)[tableView dequeueReusableCellWithIdentifier:couponTableViewCellIdentifier];
    if (cell == nil) {
        NSArray *array = [[NSBundle mainBundle] loadNibNamed:K_cellIdentifier owner:self options:nil];
        cell = [array objectAtIndex:0];
    }
    RouteEntity *entity = [mutableArrayRouteProduce objectAtIndex:indexPath.row];
    
//    [cell.viewBG.layer setMasksToBounds:YES];
//    [cell.viewBG.layer setCornerRadius:5.0]; //设置矩形四个圆角半径
//    [cell.viewBG.layer setBorderWidth:1.0]; //边框宽度
//    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
//    CGColorRef colorref = CGColorCreate(colorSpace,(CGFloat[]){ 0.77, 0.77, 0.77, 1 });
//    [cell.viewBG.layer setBorderColor:colorref];//边框颜色
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    cell.imageViewProduce.imageURL = [NSURL URLWithString:entity.t_image_url];
    
    cell.labelTitle.text = entity.t_name;
    cell.labelSubTitle.text = entity.t_service;
    cell.labelPrice.text = [NSString stringWithFormat:@"%@元", entity.t_price] ;
    
    NSString *old_price = [NSString stringWithFormat:@"原价：%@元", entity.t_old_price];
    cell.labelProPrice.text =  old_price;
    cell.img_height.constant = 170/(320.f-24.f)*(SCREEN_WIDTH-24.f);
    NSUInteger length = [old_price length];
    NSMutableAttributedString *attri = [[NSMutableAttributedString alloc] initWithString:old_price];
    [attri addAttribute:NSStrikethroughStyleAttributeName value:@(NSUnderlinePatternSolid | NSUnderlineStyleSingle) range:NSMakeRange(0, length)];
    
    [attri addAttribute:NSStrikethroughColorAttributeName value:[UIColor blackColor] range:NSMakeRange(0, length)];
    [cell.labelProPrice setAttributedText:attri];
    
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 250 + 170/(320.f-24.f)*(SCREEN_WIDTH-24.f) -170 -9;
}

#pragma mark -
#pragma mark Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    RouteEntity *entity = [mutableArrayRouteProduce objectAtIndex:indexPath.row];
    
    RouteDetailViewController *vc = [[RouteDetailViewController alloc]init];
    vc.routeEntity = entity;
    [self.navigationController pushViewController:vc animated:YES];
}


- (void)addFooter
{
    //__unsafe_unretained OAAnnoViewController *vc = self;
    MJRefreshFooterView *footer = [MJRefreshFooterView footer];
    footer.scrollView = self.tableViewRouteProduce;
    footer.beginRefreshingBlock = ^(MJRefreshBaseView *refreshView) {
        
        ++page;
        [self getRouteData:page RefreshView:refreshView];
        
        NSLog(@"%@----开始进入刷新状态", refreshView.class);
    };
    _footer = footer;
}

- (void)addHeader
{
    //__unsafe_unretained OAAnnoViewController *vc = self;
    MJRefreshHeaderView *header = [MJRefreshHeaderView header];
    header.scrollView = self.tableViewRouteProduce;
    
    header.beginRefreshingBlock = ^(MJRefreshBaseView *refreshView) {
        // 进入刷新状态就会回调这个Block
        [mutableArrayRouteProduce removeAllObjects];
        [self getRouteData:1 RefreshView:refreshView];
        NSLog(@"%@----开始进入刷新状态", refreshView.class);
    };
    header.endStateChangeBlock = ^(MJRefreshBaseView *refreshView) {
        // 刷新完毕就会回调这个Block
        NSLog(@"%@----刷新完毕", refreshView.class);
    };
    header.refreshStateChangeBlock = ^(MJRefreshBaseView *refreshView, MJRefreshState state) {
        // 控件的刷新状态切换了就会调用这个block
        switch (state) {
            case MJRefreshStateNormal:
                NSLog(@"%@----切换到：普通状态", refreshView.class);
                break;
                
            case MJRefreshStatePulling:
                NSLog(@"%@----切换到：松开即可刷新的状态", refreshView.class);
                break;
                
            case MJRefreshStateRefreshing:
                NSLog(@"%@----切换到：正在刷新状态", refreshView.class);
                break;
            default:
                break;
        }
    };
    [header beginRefreshing];
    _header = header;
}

- (void)doneWithView:(MJRefreshBaseView *)refreshView
{
    // 刷新表格
    [self.tableViewRouteProduce reloadData];
    // (最好在刷新表格后调用)调用endRefreshing可以结束刷新状态
    [refreshView endRefreshing];
}

- (void) getRouteData:(int) pageNo RefreshView:(MJRefreshBaseView *)refreshView {
    //    t_id：旅游项目id 必填	测试ID：1.，2，3，
    //page: 页码 必填
    //limit:分页 必填
    NSString *strPageNo = [NSString stringWithFormat:@"%d", pageNo];
    NSString *city_id = @"";
    city_id = [[AppDelegate instance].dicCurrentCity objectForKey:@"id"];
    CommonService *service = [[CommonService alloc] init];
    NSDictionary *param = [NSDictionary dictionaryWithObjectsAndKeys:
//                           travelAgeEntity.a_id, @"a_id",
                           city_id,@"c_id",
                           strPageNo, @"page",
                           @"20", @"limit", nil];
    
    [service getNetWorkData:param
                       Path:TRAVEL_LIST
                  Successed:^(id entity) {
                      NSDictionary *dic = (NSDictionary *)entity;
                      NSArray *array = [dic objectForKey:@"rows"];
                      for (NSDictionary* attributes in array) {
                          RouteEntity *entity = [[RouteEntity alloc] init];
                          entity = [entity initWithAttributes:attributes];
                          [mutableArrayRouteProduce addObject:entity];
                      }
                      
                      [self doneWithView:refreshView];
//                      dispatch_async(dispatch_get_main_queue(), ^{
//                          [self doneWithView:refreshView];
//                      });
                      
                  } Failed:^(NSInteger errorCode, NSString *message) {
                      dispatch_async(dispatch_get_main_queue(), ^{
                          [self doneWithView:refreshView];
                      });
                  }];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [MobClick beginLogPageView:@"RouteViewController"];
}
- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [MobClick endLogPageView:@"RouteViewController"];
}

- (IBAction)scanBtnClick:(id)sender
{
    ScanBarCodeViewController *mvc = [[ScanBarCodeViewController alloc]init];
    mvc.delegate = self;
    [self presentViewController:mvc animated:YES completion:^{
        
    }];
}

- (void) pushScanResultInfo:(NSString *)url
{
    NSString *roadline_id = nil;
    NSString *saler_phone = nil;
    NSArray *array = [url componentsSeparatedByString:@"&"];
    for (NSString * subString in array)
    {
        NSArray *subArray = [subString componentsSeparatedByString:@"="];
        if ([[subArray firstObject]isEqualToString:@"roadline_id"])
        {
            roadline_id = [subArray lastObject];
        }
        if ([[subArray firstObject]isEqualToString:@"saler_phone"])
        {
            saler_phone = [subArray lastObject];
        }
    }
    RouteDetailViewController *vc = [[RouteDetailViewController alloc]init];
    RouteEntity *entity = [[RouteEntity alloc]init];
    entity.t_id = roadline_id;
    vc.saler_phone = saler_phone;
    vc.routeEntity = entity;
    [self.navigationController pushViewController:vc animated:YES];
}
@end
